<template>
  <div class="city">
    <Head :title="$route.query.name? '城市切换 - '+$route.query.name :'城市选择'" :back="true"  ></Head>
    <div class="city-box">
      <div>
        <van-search
          v-model="value"
          show-action
          placeholder="请输入城市"
          @search="onSearch"
          @cancel="onCancel"
        />
      </div>
      <div v-if="flag"> 
        <van-index-bar >
            <div v-for="(l,i) in pinyins" :key="i">
              <van-index-anchor :index="l">{{l}}</van-index-anchor>
              <van-cell @click="chooseCity(item)" :title="item.name" v-for="(item,index) in list.filter(v=>v.pinyin.indexOf(l.toLowerCase())==0)" :key="index" />
            </div>
        </van-index-bar>
      </div>
      <div v-else>
         <van-cell   @click="chooseCity(item)" :title="item.name"  v-for="(item,i) in list" :key="i">  </van-cell>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data(){
    return {
      value:"",
      list:[],
      flag:true,
      pinyins:[
                "A",
                "B",
                "C",
                "D",
                "E",
                "F",
                "G",
                "H",
                "I",
                "J",
                "K",
                "L",
                "M",
                "N",
                "O",
                "P",
                "Q",
                "R",
                "S",
                "T",
                // "U",
                // "V",
                "W",
                "X",
                "Y",
                "Z",
            ]
    }
  },
  beforeRouteLeave(to,from,next){
    if(this.city){
      next()
    }else{
      this.$toast("请先选择城市")
      next(false)
    }
  },
  methods:{
    chooseCity(item){
      this.changeCity(item);
      this.$router.go(-1)
    },
    onSearch(data){
      this.flag = false;
      console.log(data)
      this.list = this.cityList.filter(item=>(item.name.indexOf(data)!==-1 || item.pinyin.indexOf(data)!==-1)  )
    },
    onCancel(){
      this.flag = true 
      this.list = [...this.cityList ]
    }
  },
  mounted(){
  //  vuex 数据缓存  
  // 城市列表有数据就暂时不去请求ajax 
  //  if(!this.cityList.length>0){
      this.$http.getmaizuo({
        k: 5407884
      },{
        'X-Host': 'mall.film-ticket.city.list'
      })
      .then(res=>{
          this.changeCityList(res.data.cities)   // cityList 
          this.list = res.data.cities
      })
  //  }
    
  }

}
</script>


<style lang="scss" scoped>
.city{
  width:100%;
  height:100%;
}
.city-box{
  width:100%;
  height:100%;
  overflow: auto;
}
</style>


